import {
	hGroupBy
} from "../tool/helper.js";

import axios from 'axios';


export class iaxios {
	_api;
	constructor(basicHost) {
		let tk = "";
		const config = {
			baseURL: basicHost, //',
			timeout: -1,
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded',
				'Authorization': tk,
			},
		};
		let burl = basicHost;

		const api = axios.create(config);
		api.setTK = tk => {
			localStorage.setItem("jdtk", tk);
		}
		// 默认 post 请求，使用 application/json 形式
		//api.defaults.headers.post['Content-Type'] = 'application/json';
		api.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

		//request请求拦截器 
		api.interceptors.request.use(config => {
				// 这里判断localStorage里面是否存在token，如果有则在请求头里面设置
				let tk = localStorage.getItem("jdtk")
				if (tk) {
					config.headers.Authorization = tk;
				}
				return config
			},
			err => {
				return Promise.reject(err)
			}
		);

		// http response 响应拦截器
		api.interceptors.response.use(response => {
			//拦截响应，做统一处理
			//console.log("拦截响应", response.status);
			if (response.data.code) {
				switch (response.status) {
					case 401:
						alert('无权访问');
						break;
					case 301:
						console.log('登录过期');
						// store.state.isLogin = false
						// router.replace({
						//   path: 'login',
						//   query: {
						//     redirect: router.currentRoute.fullPath
						//   }
						// })
				}
			}
			return response.data;
		}, (err, a) => { //接口错误状态处理，也就是说无响应时的处理
			console.log("异常", err, config.baseURL);
			return Promise.reject(err) // 返回接口返回的错误信息
		});

		api.hDo = function({
			dat,
			method,
			param,
			del
		}) {
			let url = `${burl}/${param}`;
			let d = dat || ""; //(dat ? JSON.stringify(dat) : "");
			if (del) {
				url = url.replaceAll(del, "");
				d = dat;
			}

			//console.log("请求", method, url, d, tk);
			return api({
				method: method || 'GET',
				url: url,
				data: d,
				timeout: -1,
				headers: {
					'Content-Type': 'application/json;charset=utf-8',
					//'Content-Type': 'application/x-www-form-urlencoded', 
					//'Accept': '*/*',
					// 'User-Agent':'Apipost client Runtime/+https://www.apipost.cn/'
				},
			});
		}

		/**
		 * 同步登录
		 */
		api.hLogin = async (user, back) => {
			var dat;
			await api.get(null, user).then((result) => {
				dat = result; //.data;
				console.log("同步登录1：", user, dat);
			});

			var d = {
				result: dat.length == 1,
				dat: null
			};
			if (d.result) {
				console.log("同步登录：", dat);
				d.dat = dat[0];
				var tick = Date.now() - new Date(d.dat.EndDate);
				if (tick >= 0) {
					d.result = false;
					d.dat = "试用时间已到!请联系管理员";
				}

			} else {
				d.dat = "请检查用户名与密码";
			}
			//console.log("同步登录2：", d);
			back(d);
		}


		api.hDoGet2 = (dat, url, back) => {

			return new Promise((resolve, reject) => {
				//console.log("****************************");
				axios({
					method: 'get',
					url: url,
					responseType: 'blob', //响应类型为流
					onDownloadProgress: (e) => { //用来计算下载量（实际项目中可以用来显示下载进度）
						let total = e.total;
						let load = e.loaded;
						console.log("total:" + total + ".load:" + load);
					}
				}).then(response => {
					if (response.status == 200) {
						//根据实际情况进行更改
						resolve(response)
					} else {
						reject(response)
					}
				})
			}).then((t) => {
				back(t);
			});
		}

		api.hFileUpload = (file, param, ProgressUpload, back) => {
			tk = localStorage.getItem("jdtk");
			//	const file = document.getElementById('file').files[0];

			var fdata = new FormData();
			fdata.append('file', file);

			//		console.log("上传文件", fdata, file);
			var xhr = new XMLHttpRequest();
			xhr.open('POST', `${burl}/${param}`);

			xhr.setRequestHeader("Authorization", tk);
			//xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
			//ajax返回
			xhr.onreadystatechange = (r) => {
				if (xhr.readyState == 4 && xhr.status == 200) {
					//console.log(dat);
					let dat = JSON.parse(xhr.responseText);
					back?.(dat);
					//	console.log("已保存", dat, file);
				}
			};
			xhr.onerror = (e) => {
				console.log("上传异常", e);
			}
			//设置超时时间
			xhr.timeout = 1000 * 60 * 5;
			xhr.ontimeout = (event) => {
				alert('请求超时！');
			};

			//监听上传属性的上传事件,
			if (xhr.upload)
				xhr.upload.onprogress = e => {
					ProgressUpload?.((e.loaded / e.total * 100).toFixed(0)); //e); //
				};
			//发送请求
			xhr.send(fdata);
		}
		this._api = api;
		return api;
	}
}



/**
 *  const file = document.getElementById('file').files[0];
    var form = new FormData();
    form.append('file', file);

    // type 1
    axios.post('http://localhost:7787/files', form).then(res => {
        console.log(res.data);
    })
    // type 2
    fetch('http://localhost:7787/files', {
        method: 'POST',
        body: form
    }).then(res => res.json()).tehn(res => {console.log(res)});
    // type3
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'http://localhost:7787/files', true);
    xhr.onload = function () {
        console.log(xhr.responseText);
    };
    xhr.send(form);
 */